<?php
/*
setAppid()
setCustomerId()

//$token = Mage::getModel('vipluxlogin/token');
//$token->setAppid(10001);
//$token->setCustomerId(100);
//$token->save();

if($token && $token->getCustomerId())
{
    
}
*/
class Silk_Mapi_Model_Token extends Mage_Core_Model_Abstract
{
    protected function _construct() {
       $this->_init("mapi/token");
    }

    public function loadByCustomer($customer)
    {
        $collection = $this->getCollection();
        $collection->addFieldToSelect('*');
        $collection->addFieldToFilter('customer_id', array('eq'=>$customer->getId()));
        $collection->load();

        if($collection && $collection->count())
        {
            return $collection->getFirstItem();
        }
        return $this;
    }

    public function loadByToken($token, $secret = '')
    {
        $collection = $this->getCollection();
        $collection->addFieldToFilter('token',array('eq'=>$token));
        if($secret)
        {
            $collection->addFieldToFilter('secret',array('eq'=>$secret));
        }
        $collection->load();
        if($collection && $collection->count())
        {
            return $collection->getFirstItem();
        }
        return $this;
    }

    public function _beforeSave() {
        parent::_beforeSave();
        //每次保存都刷新token
        if(!$this->getId())
        {
            $this->setToken($this->_generateRandomString(40));
            $this->setTokenSecret($this->_generateRandomString(32));
            $this->setAuthorized(1);
        }
        return $this;
    }

    protected function _generateRandomString($length=32)
    {
        if (function_exists('openssl_random_pseudo_bytes')) {
            // use openssl lib if it is install. It provides a better randomness
            $bytes = openssl_random_pseudo_bytes(ceil($length/2), $strong);
            $hex = bin2hex($bytes); // hex() doubles the length of the string
            $randomString = substr($hex, 0, $length); // we truncate at most 1 char if length parameter is an odd number
        } else {
            // fallback to mt_rand() if openssl is not installed
            /** @var $helper Mage_Core_Helper_Data */
            $helper = Mage::helper('core');
            $randomString = $helper->getRandomString(
                $length, Mage_Core_Helper_Data::CHARS_DIGITS . Mage_Core_Helper_Data::CHARS_LOWERS
            );
        }

        return strtoupper($randomString);
    }
}
	 